<template>
  <div ref="propertyPanel" class="property-panel">
    <el-collapse v-model="activeName" accordion>
      <el-collapse-item title="流程属性" name="1">
        <el-form
          :model="flowData"
          label-width="80px"
          label-position="right"
          style="width:90%;margin:0px auto;"
        >
          <!--表单区域 -->
          <!-- <el-form-item label="分类" prop="parentId">
                <organization-single-select
                  v-model="entityData.organizationId"
                  :name="entityData.organizationName"
                  @changeSelect="changeSelect"
                />
          </el-form-item>-->
          <el-form-item label="名称">
            <el-input v-model="flowData.flowName" @input="flowNameChange" />
          </el-form-item>
          <el-form-item label="编码">
            <el-input v-model="flowData.flowKey" @change="flowKeyChange" />
          </el-form-item>
        </el-form>
      </el-collapse-item>
      <el-collapse-item title="元素属性" name="2">
        <el-form
          ref="form"
          :model="elementData"
          label-width="80px"
          label-position="right"
          style="width:90%;margin:0px auto;"
        >
          <el-form-item label="标识">
            <el-input v-model="elementData.id" @input="idChange" />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="elementData.name" @input="nameChange" />
          </el-form-item>
        </el-form>
      </el-collapse-item>

      <el-collapse-item v-if="userTask" title="环节配置" name="3">
        <el-form
          ref="form"
          :model="personData"
          label-width="100px"
          label-position="right"
          style="width:90%;margin:0px auto;"
        >
          <el-form-item label="处理模式">
            <dictionary-radio-group
              v-model="nodeConfig.mode"
              :code="constant.DICTIONARY_TYPE_CODES.NODE_MODE"
              class="form-item"
            />
          </el-form-item>
          <el-form-item label="角色设置">
            <role-single-select v-model="nodeConfig.role" @changeSelect="roleSelected" />
          </el-form-item>
          <el-form-item label="指定处理人">
            <dictionary-radio-group
              v-model="nodeConfig.setAssigneeFlag"
              :code="constant.DICTIONARY_TYPE_CODES.YES_OR_NO"
              class="form-item"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              class="main-report_button"
              size="small"
              @click="resetNodeConfig"
            >重置</el-button>

            <el-button
              type="primary"
              class="main-report_button"
              size="small"
              @click="saveNodeConfig"
            >保存</el-button>
          </el-form-item>
        </el-form>
      </el-collapse-item>

      <el-collapse-item v-if="sequenceFlow" title="分支条件" name="4">
        <el-form
          ref="form"
          :model="sequenceFlowData"
          label-width="80px"
          label-position="right"
          style="width:90%;margin:0px auto;"
        >
          <el-form-item label="条件边表达式">
            <el-input v-model="sequenceFlowData.condition" @input="conditionChange" />
          </el-form-item>
        </el-form>
      </el-collapse-item>

      <el-collapse-item title="权限配置" name="5">
        <el-button
          type="primary"
          class="main-report_button"
          size="small"
          @click="saveRightConfig"
        >保存</el-button>

        <el-table :data="rightTableData" style="width: 100%" highlight-current-row border>
          <el-table-column label="区域" width="120">
            <template scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column label="可见">
            <template scope="scope">
              <dictionary-radio-group
                v-model="scope.row.visibleFlag"
                :code="constant.DICTIONARY_TYPE_CODES.YES_OR_NO"
                class="form-item"
              />
            </template>
          </el-table-column>
          <el-table-column label="只读">
            <template scope="scope">
              <dictionary-radio-group
                v-model="scope.row.readonlyFlag"
                :code="constant.DICTIONARY_TYPE_CODES.YES_OR_NO"
                class="form-item"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>

      <el-collapse-item title="监听" name="6">
        <el-button
          type="primary"
          icon="el-icon-add"
          class="main-report_button"
          size="small"
          @click="add"
        >新增</el-button>

        <listener-detail
          ref="listenerDetail"
          @add="addListener"
          @modify="modifyListener"
          @ok="refreshListenerList"
        />

        <el-table :data="listenerTableData" style="width: 100%" highlight-current-row border>
          <el-table-column
            v-for="(item, index) in columnList"
            :key="index"
            :label="item.label"
            :prop="item.prop"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :width="item.width"
            :formatter="item.formatFunc"
            :sortable="item.sortable"
          />
          <el-table-column fixed="right" label="操作" width="60">
            <template slot-scope="scope">
              <i class="el-icon-edit" @click="modify(scope.row)" />
              <i class="el-icon-delete" @click="remove(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script>

import RoleSingleSelect from '@/components/popsoft/CommonSelect/Role/Single'
import ListenerDetail from './listener'

import DictionaryRadioGroup from '@/components/popsoft/DictionarySelect/DictionaryRadioGroup'

export default {
  name: 'PropertyPanel',
  components: {
    RoleSingleSelect,
    ListenerDetail,
    DictionaryRadioGroup
  },
  props: {
    tempProcessDefinitionId: {
      type: String,
      default: '',
      required: false
    },
    processDefinitionId: {
      type: String,
      default: '',
      required: false
    }
  },
  data() {
    return {
      bpmnModeler: {},
      // 当前流程标识
      currentFlowKey: 'defaultKey',
      activeName: '1',
      // 流程数据
      flowData: {
        flowName: '',
        flowKey: ''
      },
      // 元素数据
      elementData: {
        id: '',
        name: '',
        color: null
      },
      // 默认环节设置，当无配置信息时默认设置的值
      defaultNodeConfig: {
        mode: this.constant.NODE_MODE.NORMAL,
        setAssigneeFlag: this.constant.YES_OR_NO.YES,
        role: ''

      },
      // 环节设置
      nodeConfig: {
        mode: this.constant.NODE_MODE.NORMAL,
        setAssigneeFlag: this.constant.YES_OR_NO.YES,
        role: ''

      },
      // 人员数据
      personData: {},
      // 边数据
      sequenceFlowData: {},
      // 权限数据
      rightTableData: [],
      // 监听数据
      listenerTableData: [],
      // 当前元素
      element: {},
      // 监听器列表当前行
      currentListenserRow: {},
      columnList: [
        // prop label show 必须定义， width/showOverflowTooltip/formatFunc/sortable 需要的话定义
        { prop: 'listenerName', label: '名称', show: true },
        { prop: 'categoryName', label: '类别', show: true },
        { prop: 'eventName', label: '事件', show: true, width: 100 },
        { prop: 'listenerTypeName', label: '类型', show: true, width: 120 },
        { prop: 'listenerCode', label: '编码', show: true, showOverflowTooltip: true, width: 400 }

      ],
      // 监听器排序信息
      sortInfo: {
        sort_field: 'createTime',
        sort_sortType: 'ascending'
      }

    }
  },
  computed: {
    userTask() {
      if (!this.element) {
        return
      }
      return this.element.type === 'bpmn:UserTask'
    },

    sequenceFlow() {
      if (!this.element) {
        return
      }
      return this.element.type === 'bpmn:SequenceFlow'
    }
  },
  methods: {

    // 获取环节设置
    getNodeConfig() {
      this.$api.workflow.workflowNodeConfig.getNodeConfig(this.tempProcessDefinitionId, this.element.id)
        .then(res => {
          if (res.data) {
            this.nodeConfig = res.data
          } else {
            // 若直接赋值，则会将引用指向nodeConfig，从而默认配置会被修改
            this.nodeConfig = Object.assign({}, this.defaultNodeConfig)
          }
        })
    },

    // 重置环节设置
    resetNodeConfig() {
      this.$api.workflow.workflowNodeConfig.resetNodeConfig(this.processDefinitionId, this.tempProcessDefinitionId, this.element.id)
        .then(res => {
          if (res.data) {
            this.nodeConfig = res.data
          } else {
            this.nodeConfig = Object.assign({}, this.defaultNodeConfig)
          }
        })
    },
    // 保存环节设置
    saveNodeConfig() {
      const params = Object.assign(this.nodeConfig, { processDefinitionId: this.tempProcessDefinitionId, definitionKey: this.elementData.id, name: this.elementData.name })

      this.$api.workflow.workflowNodeConfig.saveNodeConfig(params)
        .then(res => {
          this.nodeConfig = res.data
        })
    },

    // 获取权限设置
    getRightConfig() {
      this.$api.workflow.workflowRightConfig.getConfig(this.tempProcessDefinitionId, this.currentFlowKey, this.element.id)
        .then(res => {
          if (res.data) {
            this.rightTableData = res.data
            console.log('this.rightTableData', this.rightTableData)
          }
        })
    },
    // 保存权限设置
    saveRightConfig() {
      this.$api.workflow.workflowRightConfig.saveConfig(this.rightTableData)
        .then(res => {
          this.rightTableData = res.data
        })
    },

    show(bpmnModeler) {
      this.bpmnModeler = bpmnModeler
      // 获取流程定义节点
      const elementRegistry = this.bpmnModeler.get('elementRegistry')
      const processList = elementRegistry.filter(
        (item) => item.type === 'bpmn:Process'
      )
      const flowElement = processList[0]
      // 设置流程名称及标识
      const flow = flowElement.businessObject
      this.flowData.flowName = flow.name
      this.flowData.flowKey = flow.id
      // 设置当前流程标识
      this.currentFlowKey = flow.id
      // 添加监听
      this.addModelListener()
    },
    addModelListener() {
      // 监听节点选择变化
      this.bpmnModeler.on('selection.changed', e => {
        const element = e.newSelection[0]
        this.element = element

        if (!element) return
        this.elementData = {
          ...element.businessObject,
          ...element.businessObject.$attrs
        }
        console.log(this.element.type)
        // 获取临时版本的监听器设置
        this.getListenerConfig()

        if (this.element.type === 'bpmn:UserTask') {
          // 获取临时版本的环节设置
          this.getNodeConfig()

          // 获取临时版本的权限设置
          this.getRightConfig()

          // // 用户任务
          // const userType = this.element.businessObject.$attrs['camunda:userType']
          // this.personData.userType = userType
          // if (userType === 'assigneeExpression') {
          //   this.personData.assigneeExpression = this.element.businessObject.$attrs['camunda:assignee']
          // } else if (userType === 'candidateGroups') {
          //   this.personData.candidateGroups = this.element.businessObject.$attrs['camunda:candidateGroups']
          // } else if (userType === 'assignee') {
          //   this.personData.assignee = this.element.businessObject.$attrs['camunda:assignee']
          // } else if (userType === 'candidateUsers') {
          //   this.personData.candidateUsers = this.element.businessObject.$attrs['camunda:candidateUsers']
          // }

          // // 临时测试
          // // const before = this.element
          // // console.log('before:', before)
          // // const bpmnFactory = this.bpmnModeler.get('bpmnFactory')
          // // const taskListenerAttr = {
          // //   event: 'create',
          // //   class: 'com.popsoft.platform.core.modules.workflow.listener.ApproverTaskListener'
          // // }
          // // const node = { 'camunda:taskListener': taskListenerAttr }
          // // const extensionElements = ExtensionElementsHelper.addEntry(this.element.businessObject, this.element, node, bpmnFactory)
          // // this.element.businessObject.extensionElements = extensionElements
          // // // this.updateProperties({ 'bpmn2:extensionElements': node })
          // // const after = this.element
          // // console.log('after:', after)
          // // console.log(this.element)
          // // const modeling = this.bpmnModeler.get('modeling')
          // // const bpmnModeler = this.bpmnModeler
          // // const bpmnFactory = bpmnModeler.get('bpmnFactory')

          // // let extensionElements = {}

          // // // 判断是否存在扩展元素
          // // if (!this.element.businessObject.extensionElements) {
          // //   // 不存在，新建
          // //   extensionElements = bpmnFactory.create('bpmn:ExtensionElements')
          // //   extensionElements.$parent = this.element
          // //   // 创建监听器
          // //   const taskListenerAttr = {
          // //     event: 'create',
          // //     class: 'com.popsoft.platform.core.modules.workflow.listener.ApproverTaskListener'
          // //   }
          // //   // 添加xml节点

          // //   const moddle = this.bpmnModeler.get('moddle')
          // //   const listener = bpmnFactory.create('camunda:taskListener', taskListenerAttr)
          // //   listener.$parent = extensionElements
          // // }
          // // 更新节点属性
          // // this.updateProperties({ 'extensionElements': extensionElements })

          // // extensionElements = this.element.businessObject.extensionElements
          // // let extensionElements = modeling.getPropertie(this.element, 'extensionElements')

          // // console.log(extensionElements)
          // // console.log(this.element)
        } else if (this.element.type === 'bpmn:SequenceFlow') {
          // 条件边
          // 填充表达式默认值
          if (this.element.businessObject.conditionExpression && this.element.businessObject.conditionExpression.body) {
            this.sequenceFlowData.condition = this.element.businessObject.conditionExpression.body
          }
        }

        // if (this.form.userType === "candidateUsers") {
        //   this.form["candidateUsers"] =
        //     this.form["candidateUsers"].split(",") || [];
        // }
      })

      //  监听节点属性变化
      this.bpmnModeler.on('element.changed', e => {
        const { element } = e
        if (!element) return
        //  新增节点需要更新回属性面板
        if (element.id === this.elementData.id) {
          this.elementData.name = element.businessObject.name
          this.elementData = { ...this.elementData }
        }
      })
    },
    // 流程名称变更
    flowNameChange(value) {
      const elementRegistry = this.bpmnModeler.get('elementRegistry')
      const flowElement = elementRegistry.get(this.flowData.flowKey)

      const modeling = this.bpmnModeler.get('modeling')
      modeling.updateProperties(flowElement, {
        name: value
      })
    },
    // 流程标识变更
    flowKeyChange(value) {
      const elementRegistry = this.bpmnModeler.get('elementRegistry')
      const flowElement = elementRegistry.get(this.currentFlowKey)

      const modeling = this.bpmnModeler.get('modeling')
      modeling.updateProperties(flowElement, {
        id: value
      })
      this.currentFlowKey = value
    },

    // 属性面板标识，更新回流程节点
    idChange(id) {
      const modeling = this.bpmnModeler.get('modeling')
      modeling.updateLabel(this.element, id)
    },
    // 属性面板名称，更新回流程节点
    nameChange(name) {
      const modeling = this.bpmnModeler.get('modeling')
      modeling.updateLabel(this.element, name)
    },

    // 通用的更新节点属性的方法
    updateProperties(properties) {
      const modeling = this.bpmnModeler.get('modeling')
      modeling.updateProperties(this.element, properties)
    },
    //  处理人表达式
    assigneeExpressionChange(value) {
      // 更新节点属性
      this.updateProperties({ 'camunda:assignee': value })
    },

    // 条件边表达式变化
    conditionChange(value) {
      const moddle = this.bpmnModeler.get('moddle')
      const newCondition = moddle.create('bpmn:FormalExpression', {
        body: value
      })
      // 更新节点属性
      this.updateProperties({ 'conditionExpression': newCondition })
    },
    // 监听器相关
    // 获取列表
    getListenerConfig() {
      const params = Object.assign({ processDefinitionId: this.tempProcessDefinitionId, definitionKey: this.element.id }, this.sortInfo)
      this.$api.workflow.workflowListenerConfig.list(params)
        .then(res => {
          if (res.data) {
            this.listenerTableData = res.data
          } else {
            this.listenerTableData = []
          }
        })
    },
    // 刷新列表
    refreshListenerList() {
      this.getListenerConfig()
    },
    add() {
      this.$refs.listenerDetail.add(this.element.type, this.tempProcessDefinitionId, this.element.id)
    },
    modify(row) {
      this.$refs.listenerDetail.modify(row)
    },
    remove(row) {
      this.$confirm('此操作将删除数据, 是否继续?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = row.id
        this.$api.workflow.workflowListenerConfig.remove(ids)
          .then(() => {
            this.getListenerConfig()
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    addListener(row) {
      this.listenerTableData.push(row)
      // 添加xml节点
      // const moddle = this.bpmnModeler.get('moddle')

      // // 创建扩展节点
      // const extensionElements = moddle.create('bpmn:ExtensionElements')

      // const node = {
      //   'camunda:taskListener': {
      //     event: row.event,
      //     class: row.content
      //   }
      // }
      // modeling.updateProperties(extensionElements, node)

      // // 更新节点属性
      // this.updateProperties({ 'extensionElements': extensionElements })
      // console.log(this.element)
    },
    modifyListener(row) {
      this.listenerTableData.push(row)
    },
    roleSelected(value) {
      this.nodeConfig.role = value.id
    }

  }
}
</script>

<style lang="scss" scoped>
.property-panel {
  right: 0px;
  top: 0px;
  border-left: 1px solid #cccccc;
  padding: 5px 0;
  width: 100%;
  height: 100%;
}
</style>
